package com.example.hjt_java_web_homework3.controller;

import com.example.hjt_java_web_homework3.dao.UserDao;
import com.example.hjt_java_web_homework3.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Li Chun Hei
 * @date 31/10/2025
 * @description Spring MVC 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthServlet {

    @Autowired
    private UserDao userDao;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest loginRequest,
                                                     HttpServletRequest request) {
        try {
            User user = userDao.findByUsername(loginRequest.getUsername());

            if (user != null && user.getPassword().equals(loginRequest.getPassword()) && user.getEnabled()) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);

                // 创建响应数据 - Java 8 兼容方式
                Map<String, Object> userData = new HashMap<>();
                userData.put("username", user.getUsername());
                userData.put("role", user.getRole());

                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("data", userData);

                System.out.println("User logged in: " + loginRequest.getUsername());
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户名或密码错误");

                System.out.println("Failed login attempt for user: " + loginRequest.getUsername());
                return ResponseEntity.status(401).body(response);
            }
        } catch (Exception e) {
            System.err.println("Error in auth request: " + e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "服务器内部错误");
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("user");
            session.invalidate();
            System.out.println("User logged out: " + (user != null ? user.getUsername() : "unknown"));
        }

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "退出成功");
        return ResponseEntity.ok(response);
    }

    // 内部请求类
    public static class LoginRequest {
        private String username;
        private String password;

        // Getter 和 Setter
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
}